const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes, Op} = require("../../models/db");

router.post('/scan/findPsBill', async ctx => {
    let tenantId = ctx.user.tenantId;
    let scanInfo = ctx.request.body.scanInfo;
    if (!scanInfo) {
        return ctx.err('未找到数据');
    }
    let ret = scanInfo.split('-');
    let transType = tool.xe.toNumber(ret[0])
    let billId = tool.xe.toNumber(ret[1])
    let tids = await db.models['tenantCompany'].findAll({
        where: {
            tenantId
        }
    })
    let companyIds = []
    tids.map(row => {
        companyIds.push(row.companyId)
    })
    // 送货小票
    if (transType === 180001) {
        let ret = await db.models['cargo'].findOne({
            where: {
                id: billId,
                tenantId: {
                    [Op.in]: companyIds
                }
            }
        })
        if (!ret) {
            return ctx.err('未找到送货小票数据');
        }
        let model = ret.toJSON()
        if(model.state === 2) {
            model.state = '已确认'
        }
        if(model.state === 1) {
            model.state = '配送中'
        }
        if (model.state === 3) {
            return  ctx.err('该票据已删除')
        }
        let sql = `
        SELECT * from 
        (
            select invId,sum(qty) qty,invName,spec,unit1,unit2 from (
                select  b.cargoId,(c.qty*c.calNum) qty,c.invId,c.invName,c.spec,c.unit1,c.unit2 from cargo a inner join cargo_invoice b on a.id=b.cargoId  
                inner join v_main_info c on b.iid=c.iid and a.id=${billId}
            ) a GROUP BY invId,invName,spec,unit1,unit2
        ) a 
        `
        model.goods = await db.query(sql, {type: QueryTypes.SELECT})
        return ctx.suc('', model);
    }
    return ctx.err('还未更新此类票据信息')
})


module.exports = router;
